package com.mamingchao.concurrent.cas;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by mamingchao on 2020/7/14.
 */
public class ReadWriteLockTest2 {

    static ReentrantLock lock = new ReentrantLock();

    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();
    static int value = 0;


    static void writeValue(Lock lock,String threadName, int newValue) {
        try {

            lock.lock();
            sleepOneSencond();
            System.out.printf("线程 %s 写了new value, 新值为 %s",threadName, newValue);
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    static void readValue(Lock lock, String threadName) {
        try {

            lock.lock();
            sleepOneSencond();
            System.out.printf("线程 %s 读取了value, value 值为 %d",threadName, value);
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    private static void sleepOneSencond() {
        try{
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {

//        Runnable task1 = () -> readValue(lock);
//        Runnable task2 = () -> writeValue(lock,new Random().nextInt(10));

        Runnable task1 = () -> readValue(readLock,Thread.currentThread().getName());
        Runnable task2 = () -> writeValue(writeLock,Thread.currentThread().getName(),new Random().nextInt(10));

        for (int i= 0;i<20;i++) {
            new Thread(task1,"RT-" + i).start();
        }

        for (int i= 0;i<2;i++) {
            new Thread(task2, "WT-" + i).start();
        }

    }
}
